﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using UnityEngine;
using System;
using System.Threading.Tasks;
using System.Threading;

public class KFPing
{
    List<string> ipList = new List<string>();

    public delegate void PingComplete(List<string> ips);
    
    public PingComplete OnComplete;
    int pingnum = 0;
    public KFPing()
    {

    }
    public void Start()
    {
        getIP();
    }

    public List<string> getIPAddres()
    {
        return ipList;
    }
    public bool IsPing()
    {
        return pingnum == 255;
    }

    public void getIP()
    {
        pingnum = 0;
        ipList = new List<string>();

        //获取本地机器名 
        string _myHostName = Dns.GetHostName();
        //获取本机IP  IP6 or IP4
        string _myHostIP = Dns.GetHostEntry(_myHostName).AddressList[0].ToString();
        if (_myHostIP.IndexOf(".") < 0)
            _myHostIP = Dns.GetHostEntry(_myHostName).AddressList[1].ToString();

 
        //截取IP网段
        string ipDuan = _myHostIP.Remove(_myHostIP.LastIndexOf('.'));

        //局网 
        for (int i = 1; i <= 255; i++)
        {
            string pingIP = ipDuan + "." + i.ToString();
            Thread m_ReciveThread = new Thread(toPingIP);
            m_ReciveThread.Start(pingIP);
        }

    }

    public void toPingIP(object ipDuan)
    {
       
        System.Net.NetworkInformation.Ping myPing = new System.Net.NetworkInformation.Ping();
        PingReply reply1 = myPing.Send((string)ipDuan);
        if (reply1.Status == IPStatus.Success)
            ipList.Add((string)ipDuan);

        pingnum++; 

        Debug.Log("ping---");
        if(IsPing())
          if(OnComplete!=null)
               OnComplete(ipList);
    }

}
